const express = require('express')
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express()

// 使用 cors 中间件
app.use(cors()); // 允许所有域进行跨域请求

// 使用body-parser中间件解析请求体数据
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/', function (req, res) {
    console.log(req.body,'req.body')
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });
    const fs = require('fs');

    try {
      const data = fs.readFileSync('./123.txt', 'utf8');
      const total = data.length
      let current = 0
      let time = setInterval(() => {
        if(current>=total){
            console.log('end')
            clearInterval(time)
            return res.end()
        }
        res.write('event:lol\n')
        res.write(`data:${data.split('')[current]}\n\n`)
        current++
      }, 1000);
    } catch (err) {
      console.error(err);
    }
})

app.listen(3001)